package com.brian.mongo.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.support.atomic.RedisAtomicLong;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.TimeUnit;

/**
 * @program: architect
 * @author: Brian Huang
 * @create: 2019-08-10 16
 **/
@RestController
public class OrderIdController {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @GetMapping("/order")
    public ResponseEntity<String> order(String key, Long timeOut) {
        RedisAtomicLong redisAtomicLong = new RedisAtomicLong(key, stringRedisTemplate.getConnectionFactory());
       // redisAtomicLong.set(1);
        // 设置redis步长增长为2
//        redisAtomicLong.addAndGet(1);
        // for (int i = 0; i < 100; i++) {
        long andIncrement = redisAtomicLong.getAndIncrement();
        String orderId = prefix() + String.format("%1$05d", andIncrement);
        String insertSQL = "insert into orderNumber value('" + orderId + "');";
        // System.out.println(Thread.currentThread().getName() +
        // ",insertSQL:" + insertSQL);
        System.out.println(insertSQL);
        if ((null == redisAtomicLong || redisAtomicLong.longValue() == 0) && timeOut > 0) {// 初始设置过期时间
            redisAtomicLong.expire(timeOut, TimeUnit.SECONDS);
        }

        // }
        return new ResponseEntity<>(orderId, HttpStatus.OK);
    }


    private String prefix(){
        DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS");
        String dateTime = LocalDateTime.now(ZoneOffset.of("+8")).format(format);
        return dateTime.toString();
    }

    public static void main(String[] args) {
        String prefix = new OrderIdController().prefix();
        System.out.println(prefix);
    }

}
